<template>
  <f7-page
      :name="name"
      @page:init="onPageInit"
      @page:beforein="onPageBeforeIn"
      @page:afterin="onPageAfterIn"
      @page:beforeout="onPageBeforeOut"
      @page:afterout="onPageAfterOut">

    <f7-navbar :title="`${user.firstName} ${user.lastName}`"
               back-link="Back"></f7-navbar>
    <f7-block strong>
      {{user.about}}
    </f7-block>
    <f7-list>
      <f7-list-item
          :key="index"
          :link="link.url"
          :title="link.title"
          external
          target="_blank"
          v-for="(link, index) in user.links"
      ></f7-list-item>

      <f7-list-item title="send p2p" @click="onS1"></f7-list-item>
      <f7-list-item title="send p2p2" @click="onS2"></f7-list-item>
      <f7-list-item title="send team" @click="onS3"></f7-list-item>
      <f7-list-item title="foo" @click="onFoo"></f7-list-item>
      <f7-list-item title="bar" @click="onBar"></f7-list-item>
    </f7-list>
  </f7-page>
</template>
<script>
  import Log from '../mod/log.js'
  import strings from '../assets/strings'
  import Consts from '../assets/consts'
  import cordova from '../js/cordova-app'

  // import db from '../mod/db';
  import Alert from '../mod/alert'
  import Toast from '../mod/toast'

  import im from '../mod/im'
  import axios from 'axios'

  const name = strings.page["request-and-load"]
  const log = new Log(name)

  export default {
    data() {
      return {
        name: name,
        user: this.$f7route.context.user,

        sendFailedMessages: [],
        lastMsg: {},
      }
    },

    methods: {
      onCreated() {
        log.w("onCreated")
      },

      onMounted() {
        log.w("onMounted")
      },

      onPageInit() {
        log.w("onPageInit")
      },

      onPageBeforeIn() {
        log.w("onPageBeforeIn")
      },

      onPageAfterIn() {
        log.w("onPageAfterIn")

        cordova.addAndroidHook(this);

        // let times = 0;
        // let sid = setInterval(function () {
        //   if (5 === times) {
        //     clearInterval(sid)
        //   }
        //
        //   times++;
        //
        //   Toast.show({
        //     text: 'fast toast: ' + times,
        //     closeTimeout: 2000
        //   })
        //
        // }, 500)
        //
        // setTimeout(this.onAbout, 1000)
        // setTimeout(function () {
        //   Alert.dismiss();
        // }, 3000)

        axios({
          method: 'post',
          withCredentials: true,

          url: Consts.host + '/user/login',
          data: {
            mobile: Consts.mobile,
            password: Consts.password,
          }

        }).then((res) => {
          log.d(res.data)
        })

        im.setHandler(this.onHandleIM)
        console.log('im _sync: ', im.connected(), im.synced())
      },

      onHandleIM(what, arg1, arg2, obj) {
        const cwhat = Consts.im.what
        const carg1 = Consts.im.arg1
        const carg2 = Consts.im.arg2

        switch (what) {
          case cwhat.disconnect:
            log.w('im disconnected', obj)
            break;

          case cwhat.disconnectWillConnect:
            log.v('im disconnect, auto connect', obj)
            break;

          case cwhat.receive: {
            if (arg1 === carg1.success) {
              log.v(obj.session, obj)

              // [Neo] .TODO auto read message
              im.message.read(obj)

              const list = im.chatList()
              log.v('chat list', list)

            } else {
              log.e('send failed', obj.error)
            }
          }
            break;

          case cwhat.connected:
            log.v('im connected')
            break;

          case cwhat.synced:
            log.v('im synced')
            break;

          default:
            log.w('im unhandled: ', what, arg1, arg2, obj)
            break;
        }
      },

      onS1() {
        im.message.send('p2p-' + Consts.imToAccount,
            {text: 'echo: ' + new Date().getTime(),})
        .then(r => {
          this.lastMsg = r
          log.v('send', r.session, r.text)
        })
        .catch(r => {
          if ('object' === typeof r) {
            this.sendFailedMessages.push(r)
          } else {
            log.e(r)
          }
        })
      },

      onS2() {
        im.message.send('p2p-' + Consts.imAccount2,
            {text: 'echo: ' + new Date().getTime(),})
        .then(r => {
          this.lastMsg = r
          log.v('send', r.session, r.text)
        })
        .catch(r => {
          if ('object' === typeof r) {
            this.sendFailedMessages.push(r)
          } else {
            log.e(r)
          }
        })

        log.d(im.chatList())
      },

      onS3() {
        im.message.send('team-' + Consts.imToTeamId,
            {text: 'echo: ' + new Date().getTime(),})
        .then(r => {
          this.lastMsg = r
          log.v('send', r.session, r.text)
        })
        .catch(r => {
          if ('object' === typeof r) {
            this.sendFailedMessages.push(r)
          } else {
            log.e(r)
          }
        })
      },

      onFoo() {
        // im.chat.mute(Consts.imToAccount)
        // .then(r => log.v('mute', r.isAdd))
        // .catch(r => log.e('mute', r.error))
        // const list = im.chatList()
        // log.d(list)

        // im.chat.pin('p2p-' + Consts.imToAccount)
        // log.d(im.chatList())

        // im.chat.delete(this.lastMsg.session, true)
        // .then((r) => {
        //   log.d('delete then', r.length)
        // })

        // im.message.recall(this.lastMsg)
        // .then(console.log('recall done'))

        // im.message.delete(this.lastMsg, true)
        // .then(console.log('delete done'))

        im.message.forward('p2p-' + Consts.imToAccount, this.lastMsg)
        .then(console.log('forward done'))

      },

      onBar() {
        // im.chat.unmute(Consts.imToAccount)
        // .then(r => log.v('unmute', r.isAdd))
        // .catch(r => log.e('unmute', r.error))

        // im.chat.unpin('p2p-' + Consts.imToAccount)
        // log.d(im.chatList())

        // im.chat.clean()
        // .then((r) => {
        //   log.d('clean', im.chatList().length, r)
        // })

        let check = (res) => {
          return new Promise((resolve, reject) => {
            if (res.result !== 0) {
              // [Neo] .TODO toast or alert dialog
              reject(res)
            } else {
              resolve(res)
            }
          })
        }

        const data = {
          uid: 4,
          name: 'ai-' + new Date().getTime(),
          users: [1, 6],
          admins: [1]
        }

        // [Neo] .TODO change: im.group.xxx, im.group.notice.xxx
        im.api(im.group.quit, data)
        .then(check)
        .then((res) => {
          // [Neo] .TODO quit ui todo...
          log.d(res)
        }).catch((e) => {
          // [Neo] .TODO bad request or result
          log.w(e)
        })
      },

      onAbout() {
        log.v("ral about");

        const page = this;
        Alert.show({
          title: strings.alert["ral"],
          buttons: [
            {
              text: strings.button.confirm,
              onClick: page.onAlertConfirm,
            },
            {
              text: strings.button.cancel,
              onClick: page.onAlertCancel,
            },

          ]
        }, false)
      },

      onAlertConfirm(dialog, e) {
        log.d("confirm", dialog, e)
      },

      onAlertCancel(dialog, e) {
        log.d("cancel", dialog, e)
      },

      onPageBeforeOut() {
        log.w("onPageBeforeOut")

        if (im.connected()) {
          im.disconnect()
        }

        cordova.removeAndroidHook(this);
      },

      onPageAfterOut() {
        log.w("onPageAfterOut")
      },

      onDestroyed() {
        log.w("onDestroyed")
      },

      onUpdated() {
        log.w("onUpdated")
      },

      onBack() {
        log.w("onBack")
        this.$f7router.back();
      },

      onResume() {
        log.w("onResume")
      },

      onPause() {
        log.w("onPause")
      },

    }
    ,

    created() {
      this.onCreated();
    }
    ,

    updated() {
      this.onUpdated();
    }
    ,

    destroyed() {
      this.onDestroyed();
    }
    ,

    mounted() {
      this.onMounted();
    }
    ,
  }
</script>
